<template>
    <div id="LoginBox">
        <image class="LoginBox-img" src="/static/bg.jpg"></image>
        <div class="long-loading">
            {{i18n('login','登录跳转中.....')}}
        </div>
    </div>
</template>

<script>
import LoginApi from "@/api/login";
import RxPicker from '@/components/RxPicker'
import common from '@/common/constants.js';
import {
    loginBindDd,
    loginTypeMap
} from '@/common/platformLogin.js';
import TokenUtil from "../../common/TokenUtil";

export default {
    name: "PlatformLogin",
    components: {
        RxPicker
    },
    data() {
        return {
            openId: '',
            tenantId: null,
            code: null,
        }
    },
    mounted(){
        this.initData(this.$route.query);
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"pagesLoginLang",key);
        },
        initData(item) {
            if (item) {
                this.code = item.code;
                this.tenantId = item.tenantId;
            }
            if (!this.tenantId) {
                //获取消息链接储存的租户
                let tenantId_ = uni.getStorageSync('tenantId')
                this.tenantId =tenantId_?tenantId_:this.getBaseTenantId();
            }else{
                this.setBaseTenantId(this.tenantId);
            }
            //第三方平台回调
            if (this.code) {
                this.platformAutoLogin();
                return;
            }else if(this.tenantId) {
                this.getPlatformAuthUrl();
                return;
            }
            //走登录页面
            this.gotLoginPage();
        },
        //自动登陆
        platformAutoLogin() {
            //根据第三方授权返回的code,进行尝试登陆
            let loginType = loginTypeMap()[common.AppType];
            let params = {
                tenantId: this.tenantId,
                code: this.code,
                loginType: loginType
            }
            let self_ = this;
            //自动登陆
            LoginApi.platformAutoLogin(params).then(res => {
                //返回成功，则跳转到URL
                if (res.success) {
                    const result = res.data
                    //请求返回体加密时：token = result.value
                    let token = result.access_token || result.value;
                    TokenUtil.setTokenAsync(token,()=>{
                        //设置当前登录用户
                        self_.go2Page();
                    })
                } else{
                    uni.showToast({
                        title: res.message, // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                    //未绑定用户,跳转到账号密码登陆页
                    self_.openId = res.data;
                    self_.gotLoginPage();
                }
            })
        },
        //自动登录成功后跳转到指定页面
        go2Page(url) {
            let self_=this;
            //先后台获取用户信息
            LoginApi.currentUser().then(res => {
                if (res.success) {
                    //储存用户信息
                    uni.setStorage({key: 'user', data: res.data})
                    if (url) {
                        location.href=url ;
                        return;
                    }
                    let uniRoute = uni.getStorageSync('uniRoute')
                    uni.setStorage({key: 'uniRoute', data: ''})
                    if(uniRoute){
                        window.location.href = uniRoute;
                        return;
                    }
                    //工作台
                    uni.switchTab({
                        url: '/pages/RxWorkbench'
                    });
                }else {
                    //获取用户信息失败toke过期了重新免登录
                    uni.showToast({
                        title: '获取toke失败', // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                }
            })
        },
        gotLoginPage() {
            let url = common.LoginPage + "?openId=" + this.openId;
            uni.navigateTo({url: url})
        },
        //钉钉登录--获取跳转第三方授权地址
        getPlatformAuthUrl(redirectUrl) {
            let self = this;
            //先从后台获取企业微信授权访问地址
            let tenantId = this.getBaseTenantId();
            if(!tenantId){
                tenantId =this.tenantId;
            }
            //获取全路径
            let url = this.getUrl("pages/RxLogin/PlatformLogin");
            if (redirectUrl) {
                url = redirectUrl;
            }
            //钉钉直接调用sdk
            if (common.AppType == common.TypeDd) {
                loginBindDd(common.PlatformLoginPage,this.tenantId);
                return;
            } else {
                if(url.indexOf("tenantId")==-1){
                    url = url +"?tenantId="+this.tenantId;
                }
                let loginType = loginTypeMap()[common.AppType];
                let params = {
                    tenantId: tenantId,
                    redirectUrl: encodeURIComponent(url),
                    loginType: loginType,
                    state: '',
                    paramType:"mobile"
                }
                /**
                 * 1、回调url进行了编码
                 * 2、如果是飞书，则后台需要将url进行解码，因为飞书的回调url不支持encodeURIComponent
                 */
                if(loginType == 3){
                    params.redirectUrl =url;
                }
                TokenUtil.removeToken();
                LoginApi.getAuthUrl(params).then(res => {
                    //返回成功，则跳转到URL
                    if (res.success && res.data) {
                        window.location.href = res.data;
                        return;
                    }else{
                        self.gotLoginPage();
                    }
                })
            }
        },
        getUrl(uri) {
            let routes = getCurrentPages();
            let curRoute = routes[routes.length - 1].route;
            let loginUrl = location.href.split(curRoute)[0] + uri;
            return loginUrl
        }
    }
}
</script>

<style scoped>
.LoginBox-img {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 0;
}

.LoginBox-img img {
    width: 100%;
}


#LoginBox {
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.long-loading {
    width: 100%;
    text-align: center;
    margin-top: 1rem;
    position: absolute;
    z-index: 999;
    color: #FFFFFF;
}
</style>
